package com.deyuanyun.pic.pbf.service.impl;

import com.deyuanyun.pic.common.spring.SpringAppliction;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.pbf.controller.dto.defect.DefectStatisticsDto;
import com.deyuanyun.pic.pbf.controller.dto.defect.measure.*;
import com.deyuanyun.pic.pbf.controller.dto.defect.node.*;
import com.deyuanyun.pic.pbf.controller.dto.defect.repair.*;
import com.deyuanyun.pic.pbf.domain.*;
import com.deyuanyun.pic.pbf.enumeration.DefectMeasureMethod;
import com.deyuanyun.pic.pbf.enumeration.DefectRepairMethod;
import com.deyuanyun.pic.pbf.enumeration.DefectRepairNode;
import com.deyuanyun.pic.pbf.mapper.DefectInfoMapper;
import com.deyuanyun.pic.pbf.mapper.RepairPipeWeldingMapper;
import com.deyuanyun.pic.pbf.mapper.RepairTaskMapper;
import com.deyuanyun.pic.pbf.mapper.dao.DefectInfoDao;
import com.deyuanyun.pic.pbf.mapper.dao.DefectRepairMethodDao;
import com.deyuanyun.pic.pbf.mapper.dao.DefectRepairNodeDao;
import com.deyuanyun.pic.pbf.service.DefectRepairMgrService;
import com.deyuanyun.pic.pbf.service.RepairPipeWeldingService;
import com.deyuanyun.pic.pbf.service.RepairTaskService;
import com.deyuanyun.pic.settings.domain.base.Code;
import com.deyuanyun.pic.settings.support.biz.CodeUtil;
import com.deyuanyun.pic.wf.domain.TaskInstance;
import com.deyuanyun.pic.wf.mapper.TaskInstanceMapper;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 缺陷修复流程管理服务
 *
 * @author hlw
 * @date
 *
 * History: [修改人][时间][修改描述]
 */
@Service
public class DefectRepairMgrServiceImpl implements DefectRepairMgrService {

    @Resource
    private DefectRepairMethodDao defectRepairMethodDao;
    @Resource
    private DefectRepairNodeDao defectRepairNodeDao;
    @Resource
    private DefectInfoDao defectInfoDao;

    @Resource
    private TaskInstanceMapper taskInstanceMapper;
    @Resource
    private DefectInfoMapper defectInfoMapper;
    @Resource
    private RepairTaskMapper repairTaskMapper;

    private Logger logger = LogManager.getLogger(this.getClass());

    @Override
    public List<DefectInfo> queryDefectInfoList() {
        return defectInfoDao.queryDefectInfoList();
    }

    @Override
    public List<TaskInstance> queryTaskInstanceList(String defectId) {

        if (StringUtils.isNullEmpty(defectId)) {
            return null;
        }
        return defectInfoDao.queryTaskInstanceList(defectId);
    }

    @Override
    public Object findRepairNode(String taskInstanceId) {
        return getDefectRepairNode(taskInstanceMapper.selectByPrimaryKey(taskInstanceId));
    }

    @Override
    public DefectStatisticsDto getDefectStatistics(String repairTaskId){
        DefectStatisticsDto defectStatisticsDto = new DefectStatisticsDto();
        defectStatisticsDto.fromDomain(repairTaskMapper.selectByPrimaryKey(repairTaskId));
        defectStatisticsDto.fromDefectStatistics(defectInfoDao.getDefectStatistics(repairTaskId));
        return defectStatisticsDto;
    }

    @Override
    public List<Map<DefectRepairNode, Object>> queryRepairNode(String defectId) {

        // 1,根据defectId 获得该缺陷对应的维修节点TaskInstance
        // 2,根据TaskInstance对象找到数据存储的表单，并取出对应的数据
        // 3,根据“缺陷类型”返回 对应的“缺陷检测信息”
        // 4,根据“维修方法”返回对应“维修信息”

        List<Map<DefectRepairNode, Object>> list = new ArrayList();
        List<TaskInstance> taskInstanceList = defectInfoDao.queryTaskInstanceList(defectId);
        for (TaskInstance taskInstance : taskInstanceList) {
            Map<DefectRepairNode, Object> defectRepairNodeMap = this.getDefectRepairNode(taskInstance);
            if (defectRepairNodeMap != null) {
                list.add(defectRepairNodeMap);
            }
        }

        return list;
    }

    private Map addDefectNode(DefectRepairNode defectRepairNode, Object o) {
        Map<DefectRepairNode, Object> map = new HashMap<DefectRepairNode, Object>();
        map.put(defectRepairNode, o);
        return map;
    }


    /**
     * 得到缺陷维修节点
     *
     * @param taskInstance
     * @return
     */
    private Map<DefectRepairNode, Object> getDefectRepairNode(TaskInstance taskInstance) {

        if (ObjectUtil.isEmptyAll(taskInstance)){
            return null;
        }

        String taskInstanceId = taskInstance.getId();
        String nodeType = taskInstance.getNodeType();
        Short isCompletion = taskInstance.getIsCompletion();

        // 1,判断是否是：管沟开挖
        if (DefectRepairNode.START_NODE.toString().equals(nodeType)) {
            logger.debug("----------->加载缺陷管理-【管沟开挖】节点数据");
            TrenchExcavationDto trenchExcavationDto = new TrenchExcavationDto(isCompletion);
            trenchExcavationDto.fromDomain(defectRepairNodeDao.findTrenchExcavation(taskInstanceId));
            return this.addDefectNode(DefectRepairNode.START_NODE, trenchExcavationDto);
        }
        // 2,判断是否是：腐蚀环境调查
        if (DefectRepairNode.CORROSION_ENVIRONMENT_NODE.toString().equals(nodeType)) {
            logger.debug("----------->加载缺陷管理-【腐蚀环境调查】节点数据");
            CorrosionEnvironmentDto corrosionEnvironmentDto = new CorrosionEnvironmentDto(isCompletion);
            corrosionEnvironmentDto.fromDomain(defectRepairNodeDao.findCorrosionEnvironment(taskInstanceId));
            return this.addDefectNode(DefectRepairNode.CORROSION_ENVIRONMENT_NODE, corrosionEnvironmentDto);
        }
        // 3,判断是否是：防腐层调查
        if (DefectRepairNode.COAT_SURVEY_NODE.toString().equals(nodeType)) {
            logger.debug("----------->加载缺陷管理-【防腐层调查】节点数据");
            CoatSurveyDto coatSurveyDto = new CoatSurveyDto(isCompletion);
            coatSurveyDto.fromDomain(defectRepairNodeDao.findCoatSurvey(taskInstanceId));
            return this.addDefectNode(DefectRepairNode.COAT_SURVEY_NODE, coatSurveyDto);
        }
        // 4,判断是否是：表面处理
        if (DefectRepairNode.SURFACE_TREATMENT_NODE.toString().equals(nodeType)) {
            logger.debug("----------->加载缺陷管理-【表面处理】节点数据");
            SurfaceTreatmentDto surfaceTreatmentDto = new SurfaceTreatmentDto(isCompletion);
            surfaceTreatmentDto.fromDomain(defectRepairNodeDao.findSurfaceTreatment(taskInstanceId));
            return this.addDefectNode(DefectRepairNode.SURFACE_TREATMENT_NODE, surfaceTreatmentDto);
        }
        // 5,判断是否是：阴保调查
        if (DefectRepairNode.CP_SURVEY_NODE.toString().equals(nodeType)) {
            logger.debug("----------->加载缺陷管理-【阴保调查】节点数据");
            CPSurveyDto cpSurveyDto = new CPSurveyDto(isCompletion);
            cpSurveyDto.fromDomain(defectRepairNodeDao.findCPSurvey(taskInstanceId));
            return this.addDefectNode(DefectRepairNode.CP_SURVEY_NODE, cpSurveyDto);
        }
        // 6,判断是否是：缺陷测量
        if (DefectRepairNode.DEFECT_MEASURE_NODE.toString().equals(nodeType)) {
            logger.debug("----------->加载缺陷管理-【缺陷测量】节点数据");
            DefectMeasure defectMeasure = defectRepairNodeDao.findDefectMeasure(taskInstance.getDefectInfoId());
            return this.addDefectNode(DefectRepairNode.DEFECT_MEASURE_NODE, this.getDefectMeasureMethod(defectMeasure, taskInstance));
        }
        // 7.判断是否是：缺陷维修
        if (DefectRepairNode.REPAIR_NODE.toString().equals(nodeType)) {
            logger.debug("----------->加载缺陷管理-【缺陷维修】节点数据");
            return this.addDefectNode(DefectRepairNode.REPAIR_NODE, this.getDefectRepairMethod(taskInstance));
        }
        // 7.判断是否是：缺陷维修-换管-焊接
        if (DefectRepairNode.HG_REPAIR_NODE.toString().equals(nodeType)) {
            logger.debug("----------->加载缺陷管理-【缺陷维修-换管-焊接】节点数据");
            RepairPipeWeldingVO repairPipeWeldingVO = new RepairPipeWeldingVO(isCompletion);
            repairPipeWeldingVO.fromDomain(defectRepairMethodDao.findRepairPipeWelding(taskInstanceId));
            return this.addDefectNode(DefectRepairNode.HG_REPAIR_NODE, repairPipeWeldingVO);
        }
        // 8,判断是否是：防腐层修复
        if (DefectRepairNode.COAT_REPAIR_NODE.toString().equals(nodeType)) {
            logger.debug("----------->加载缺陷管理-【防腐层修复】节点数据");
            CoatRepairDto coatRepairDto = new CoatRepairDto(isCompletion);
            coatRepairDto.fromDomain(defectRepairNodeDao.findCoatRepair(taskInstanceId));
            return this.addDefectNode(DefectRepairNode.COAT_REPAIR_NODE, coatRepairDto);
        }
        // 9,判断是否是：管沟回填
        if (DefectRepairNode.END_NODE.toString().equals(nodeType)) {
            logger.debug("----------->加载缺陷管理-【管沟回填】节点数据");
            TrenchBackPillDto trenchBackPillDto = new TrenchBackPillDto(isCompletion);
            trenchBackPillDto.fromDomain(defectRepairNodeDao.findTrenchBackPill(taskInstanceId));
            return this.addDefectNode(DefectRepairNode.END_NODE, trenchBackPillDto);
        }
        return null;
    }

    /**
     * 得到修复方法
     *
     * @return
     */
    private Object getDefectRepairMethod(TaskInstance taskInstance) {

        String tabName = taskInstance.getTabName();
        Short isCompletion = taskInstance.getIsCompletion();
        String nodeName = taskInstance.getNodeName();

        //  1，判断修复方式是否是：复合材料补强修复
        if (DefectRepairMethod.COMPOSITES.getMethod().equals(tabName)) {
            logger.debug("----------->加载缺陷管理-【缺陷维修->复合材料补强修复】节点数据");
            RepairCompositesDto repairCompositesDto = new RepairCompositesDto(isCompletion);
            repairCompositesDto.setNodeName(nodeName);
            repairCompositesDto.fromDomain(defectRepairMethodDao.findRepairComposites(taskInstance.getId()));
            repairCompositesDto.setRepairMethodCode(DefectRepairMethod.COMPOSITES.getMethod());
            return repairCompositesDto;
        }
        // 2，判断修复方式是否是：钢质环氧套筒补强修复
        if (DefectRepairMethod.EPOXY_SLEEVE.getMethod().equals(tabName)) {
            logger.debug("----------->加载缺陷管理-【缺陷维修->钢质环氧套筒补强修复】节点数据");
            RepairEpoxySleeveDto repairEpoxySleeveDto = new RepairEpoxySleeveDto(isCompletion);
            repairEpoxySleeveDto.setNodeName(nodeName);
            repairEpoxySleeveDto.fromDomain(defectRepairMethodDao.findRepairEpoxySleeve(taskInstance.getId()));
            repairEpoxySleeveDto.setRepairMethodCode(DefectRepairMethod.EPOXY_SLEEVE.getMethod());
            return repairEpoxySleeveDto;
        }
        // 3，判断修复方式是否是：A型套筒补强修复 或者 B型套筒补强修复
        if (DefectRepairMethod.ATYPE_SLEEVE.getMethod().equals(tabName)
                || DefectRepairMethod.BTYPE_SLEEVE.getMethod().equals(tabName)) {
            logger.debug("----------->加载缺陷管理-【缺陷维修->A型套筒补强修复 或者 B型套筒补强修复】节点数据");
            RepairABTypeSleeveDto repairABTypeSleeveDto = new RepairABTypeSleeveDto(isCompletion);
            repairABTypeSleeveDto.setNodeName(nodeName);
            repairABTypeSleeveDto.fromDomain(defectRepairMethodDao.findRepairABTypeSleeve(taskInstance.getId()));
            repairABTypeSleeveDto.setRepairMethodCode(DefectRepairMethod.ATYPE_SLEEVE.getMethod());
            return repairABTypeSleeveDto;
        }
        // 4，判断修复方式是否是：换管
        if (DefectRepairMethod.REPLACE_PIPE.getMethod().equals(tabName)) {
            logger.debug("----------->加载缺陷管理-【缺陷维修->换管】节点数据");
            RepairReplacePipeDto repairReplacePipeDto = new RepairReplacePipeDto(isCompletion);
            repairReplacePipeDto.setNodeName(nodeName);
            repairReplacePipeDto.fromDomain(defectRepairMethodDao.findRepairReplacePipe(taskInstance.getId()));
            repairReplacePipeDto.setRepairMethodCode(DefectRepairMethod.REPLACE_PIPE.getMethod());
            return repairReplacePipeDto;
        }
        // 5，判断修复方式是否是：其他自定义修复方法
        if (DefectRepairMethod.OTHER.getMethod().equals(tabName)) {
            logger.debug("----------->加载缺陷管理-【缺陷维修->其他自定义修复方法】节点数据");
            RepairOtherDto repairOtherDto = new RepairOtherDto(isCompletion);
            repairOtherDto.setNodeName(nodeName);
            repairOtherDto.fromDomain(defectRepairMethodDao.findRepairOther(taskInstance.getId()));
            repairOtherDto.setRepairMethodCode(DefectRepairMethod.OTHER.getMethod());
            return repairOtherDto;
        }
        // 6，判断修复方式是否是：开挖验证
        if (DefectRepairMethod.NODE.getMethod() == tabName) {
            logger.debug("----------->加载缺陷管理-【缺陷维修->开挖验证】节点数据");
            RepairNodeDto repairNodeDto = new RepairNodeDto(isCompletion);
            repairNodeDto.setNodeName(nodeName);
            repairNodeDto.setRepairMethodCode(DefectRepairMethod.NODE.toString());
            return repairNodeDto;
        }
        return null;
    }

    /**
     * 得到缺陷测量信息
     *
     * @param defectMeasure
     * @param taskInstance
     * @return
     */
    private Object getDefectMeasureMethod(DefectMeasure defectMeasure, TaskInstance taskInstance) {

        String defectInfoId = taskInstance.getDefectInfoId();
        Short isCompletion = taskInstance.getIsCompletion();

        DefectInfo defectInfo = defectInfoMapper.selectByPrimaryKey(defectInfoId);
        Code code = CodeUtil.getCodeById(defectInfo.getFeatureType());
        if (ObjectUtil.isEmptyAll(code)) {
            return null;
        }

        // 1,判断缺陷类型是否是：金属损失
        if (DefectMeasureMethod.TDF_FEATURE_TYPE_JSSS.toString().equals(code.getMinorCode())) {
            MetaLossMeasureDto metaLossMeasureDto = new MetaLossMeasureDto(defectInfo, isCompletion);
            metaLossMeasureDto.fromDomain(defectMeasure);
            metaLossMeasureDto.setFeatureTypeCode(DefectMeasureMethod.TDF_FEATURE_TYPE_JSSS.toString());
            return metaLossMeasureDto;
        }
        // 2,判断缺陷类型是否是：凹陷
        if (DefectMeasureMethod.TDF_FEATURE_TYPE_AX.toString().equals(code.getMinorCode())) {
            DepressedMeasureDto depressedMeasureDto = new DepressedMeasureDto(defectInfo, isCompletion);
            depressedMeasureDto.fromDomain(defectMeasure);
            depressedMeasureDto.setFeatureTypeCode(DefectMeasureMethod.TDF_FEATURE_TYPE_AX.toString());
            return depressedMeasureDto;
        }
        // 3,判断缺陷类型是否是：焊缝异常
        if (DefectMeasureMethod.TDF_FEATURE_TYPE_HFYC.toString().equals(code.getMinorCode())) {
            WeldMeasureDto weldMeasureDto = new WeldMeasureDto(defectInfo, isCompletion);
            weldMeasureDto.fromDomain(defectMeasure);
            weldMeasureDto.setFeatureTypeCode(DefectMeasureMethod.TDF_FEATURE_TYPE_HFYC.toString());
            return weldMeasureDto;
        }
        // 4,判断缺陷类型是否是：椭圆变形
        if (DefectMeasureMethod.TDF_FEATURE_TYPE_TYBX.toString().equals(code.getMinorCode())) {
            EllipticDeformMeasureDto ellipticDeformMeasureDto = new EllipticDeformMeasureDto(defectInfo, isCompletion);
            ellipticDeformMeasureDto.fromDomain(defectMeasure);
            ellipticDeformMeasureDto.setFeatureTypeCode(DefectMeasureMethod.TDF_FEATURE_TYPE_TYBX.toString());
            return ellipticDeformMeasureDto;
        }
        // 5,判断缺陷类型是否是：类裂纹
        if (DefectMeasureMethod.TDF_FEATURE_TYPE_LLW.toString().equals(code.getMinorCode())) {
            CrackMeasureDto crackMeasureDto = new CrackMeasureDto(defectInfo, isCompletion);
            crackMeasureDto.fromDomain(defectMeasure);
            crackMeasureDto.setFeatureTypeCode(DefectMeasureMethod.TDF_FEATURE_TYPE_LLW.toString());
            return crackMeasureDto;
        }
        // 6,判断缺陷类型是否是：损伤缺陷
        if (DefectMeasureMethod.TDF_FEATURE_TYPE_SSQX.toString().equals(code.getMinorCode())) {
            OtherMeasureDto otherMeasureDto = new OtherMeasureDto(defectInfo, isCompletion);
            otherMeasureDto.fromDomain(defectMeasure);
            otherMeasureDto.setFeatureTypeCode(DefectMeasureMethod.TDF_FEATURE_TYPE_SSQX.toString());
            return otherMeasureDto;
        }
        // 7,判断缺陷类型是否是：补丁信息
        if (DefectMeasureMethod.TDF_FEATURE_TYPE_BDXX.toString().equals(code.getMinorCode())) {
            PatchMeasureDto patchMeasureDto = new PatchMeasureDto(defectInfo, isCompletion);
            patchMeasureDto.fromDomain(defectMeasure);
            patchMeasureDto.setFeatureTypeCode(DefectMeasureMethod.TDF_FEATURE_TYPE_BDXX.toString());
            return patchMeasureDto;
        }
        return null;

    }

}
